import json
import os


class EcsConfig:
    def __init__(self):
        self.access_key = ''
        self.access_key_secret = ''
        self.band_width = 5
        self.ecs_password = 'QwEr1234'
        self.region_id = 'cn-hongkong'
        self.zone_id = ''
        self.instance_type = 'ecs.t5-lc2m1.nano'


class ServerConfig:
    def __init__(self):
        self.ss_password = 'ZxCv5678'
        self.ss_port = 21234
        self.ss_method = "chacha20"


class WebConfig:
    def __init__(self):
        self.port = 5000
        self.url = 'Qwer1234'


class Config:
    def __init__(self):
        self.ecs_config = EcsConfig()
        self.server_config = ServerConfig()
        self.web_config = WebConfig()


def load_config():
    file_object = open(os.path.join(os.path.split(os.path.realpath(__file__))[0], '..', 'config.json'))
    try:
        data = file_object.read()
        obj = json.loads(data)
        conf = Config()
        conf.ecs_config.__dict__ = obj['ecs_config']
        conf.server_config.__dict__ = obj['server_config']
        if 'web_config' in obj:
            conf.web_config.__dict__ = obj['web_config']

        print 'load config ok'
        print '-----------------ecs config---------------------------'
        print 'access_key         ', conf.ecs_config.access_key
        print 'access_key_secret  ', conf.ecs_config.access_key_secret
        print 'band_width         ', conf.ecs_config.band_width
        print 'ecs_password       ', conf.ecs_config.ecs_password
        print 'region_id          ', conf.ecs_config.region_id
        print 'zone_id            ', conf.ecs_config.zone_id
        print 'instance_type      ', conf.ecs_config.instance_type
        print '-----------------server config------------------------'
        print 'ss_password        ', conf.server_config.ss_password
        print 'ss_port            ', conf.server_config.ss_port
        print 'ss_method          ', conf.server_config.ss_method
        print '-----------------web config---------------------------'
        print 'port               ', conf.web_config.port
        print 'url                ', conf.web_config.url
        print '------------------------------------------------------'
        return conf
    except Exception, e:
        print 'load config failed:', e
        return None
    finally:
        file_object.close()


def reset_config():
    conf = Config()
    filename = os.path.join(os.path.split(os.path.realpath(__file__))[0], '..', 'config.json')
    if os.path.exists(filename):
        os.remove(filename)

    file_object = open(filename, 'w')
    try:
        conf.ecs_config = conf.ecs_config.__dict__
        conf.server_config = conf.server_config.__dict__
        file_object.write(json.dumps(conf.__dict__, sort_keys=True, indent=4))
        print 'config reset'
    except Exception, e:
        print 'load config failed:', e
    finally:
        file_object.close()
